package com.controller;

import com.entity.Draft;
import com.service.impl.BlogServiceImpl;
import com.service.impl.DraftServiceImpl;
import com.service.intf.BlogService;
import com.service.intf.DraftService;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class DraftServlet extends BaseServlet {
    private DraftService draftService = new DraftServiceImpl();
    private BlogService blogService = new BlogServiceImpl();

    protected void queryDraft(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer userId = (Integer) req.getSession().getAttribute("userId");
        List<Draft> drafts = draftService.queryDraftByUserId(userId);
        req.getSession().setAttribute("drafts", drafts);
        req.getRequestDispatcher("/pages/draft/draft_list.jsp").forward(req, resp);


    }

    protected void saveDraft(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
//        String  userName = (String) req.getSession().getAttribute("userName");
        Integer userId = blogService.queryUserIdByUserName(userName);

//        Integer userId= (Integer) req.getSession().getAttribute("userId");
        String draft = req.getParameter("draft");
        draftService.saveDraft(userId, draft);
        resp.sendRedirect(req.getContextPath() + "/draftServlet?action=queryDraft&userId=" + userId);
    }

    protected void releaseDraft(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        int draftId = WebUtils.parseInt(req.getParameter("draftId"), 0);
//        String draftId = req.getParameter("draftId");
        draftService.releaseDraft(draftId);
        Integer userId = blogService.queryUserIdByUserName(userName);
        resp.sendRedirect(req.getContextPath() + "/draftServlet?action=queryDraft&userId=" + userId);

    }
}